
package com.lucker.controller.caipiao;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.lucker.cds.model.CEvenyDayOpenTime;
import com.lucker.cds.model.CustomCaiPiaoOpencode;
import com.lucker.common.util.AESCBCUtil;
import com.lucker.common.util.DateTimeUtil;
import com.lucker.common.util.StringUtil;
import com.lucker.controller.BaseController;
import com.lucker.ds.model.CaiPiao;
import com.lucker.ds.model.CaiPiaoOpenTime;
import com.lucker.ds.model.CaiPiaoOpencode;
import com.lucker.ds.model.CaiPiaoOpencodeBackup;
import com.lucker.ds.model.CaiType;
import com.lucker.ds.model.SysRestrictionsConfig;
import com.lucker.framework.constant.ResponseBaseModel;
import com.lucker.framework.constant.ResponseResultModel;
import com.lucker.service.caipiao.CaiPiaoOpencodeService;
import com.lucker.service.caipiao.CaiPiaoService;
import com.lucker.service.caipiao.CaiTypeService;
import com.lucker.service.caipiaomisscodelist.CaiPiaoMissCodeListService;
import com.lucker.service.caipiaoopencodebackup.CaiPiaoOpencodeBackupService;
import com.lucker.service.evenydayopentime.EvenyDayOpenTimeService;
import com.lucker.service.mail.MailService;
import com.lucker.service.model.Mail;
import com.lucker.service.sys.SysRestrictionsConfigService;
import com.lucker.vo.CaiOpenInfo;
import com.lucker.vo.CaiOpenInfoV2;


@Controller()
@RequestMapping(value = "caipiao")
public class CaiPiaoController  extends BaseController {
	
	@Autowired 
	CaiTypeService caiTypeService;
	
	@Autowired
	CaiPiaoService caiPiaoService;
	
	@Autowired
	CaiPiaoOpencodeService caiPiaoOpencodeService;
	
	@Autowired
	CaiPiaoOpencodeBackupService caiPiaoOpencodeBackupService;
	
	@Autowired
	CaiPiaoMissCodeListService caiPiaoMissCodeListService;
	
	@Autowired
	EvenyDayOpenTimeService evenyDayOpenTimeService;
	
	@Autowired
	MailService mailService;
	
	@Autowired
	SysRestrictionsConfigService sysRestrictionsConfigService;
	
	/***
	 * 爬虫提交开奖号码
	 * @param info
	 * @return
	 */
	@RequestMapping(value="/commit_opencodev1",method = RequestMethod.GET)
	public @ResponseBody ResponseEntity<?> commit_opencodev1(HttpServletRequest req , CaiOpenInfo info) {
		try {
			if(info.getIssueNo() == null && info.getIssueNo().length() < 6) {
				return new ResponseEntity<>(new ResponseBaseModel(29002,"期号为空，或期号长度错误! "), HttpStatus.OK);
			}
			if(info != null) {
				caiPiaoService.commitCaiPiao(info.getTypeId(), info.getOpenCode(), info.getDomainName(),info.getDomainId(), info.getIssueNo(),null);
			}
			
			return new ResponseEntity<>(new ResponseBaseModel(10000,"ok"), HttpStatus.OK);
		}catch(Exception e) {
			this.getLoger().error("提交异常 {} , {}", e.getMessage(),e);
			return new ResponseEntity<>(new ResponseBaseModel(29002,e.getMessage()), HttpStatus.OK);
		}
	}
	
	
	/***
	 * 爬虫提交开奖号码 V2.0  根据建华的建议进行了修改
	 * @param info
	 * @return
	 */
	@RequestMapping(value="/commit_opencode",method = RequestMethod.GET)
	public @ResponseBody ResponseEntity<?> commit_opencode(HttpServletRequest req , CaiOpenInfoV2 info) {
		try {
			if(StringUtils.isBlank(info.getCaiId())) {
				return new ResponseEntity<>(new ResponseBaseModel(29002,"参数cai_id 不能为空"), HttpStatus.OK);
			}
			if(info.getIssueNo() == null && info.getIssueNo().length() < 8) {
				return new ResponseEntity<>(new ResponseBaseModel(29002,"期号为空，或期号长度错误! "), HttpStatus.OK);
			}
			if(info != null) {
				getLoger().error("PYTHON 提交的开奖号码  :  {} ", JSONObject.toJSONString(info));
				caiPiaoService.commitCaiPiao(info.getOpenCode(), info.getSource(), info.getIssueNo(),info.getCommitTime(), info.getCaiId());
			}
			
			return new ResponseEntity<>(new ResponseBaseModel(10000,"ok"), HttpStatus.OK);
		}catch(Exception e) {
			this.getLoger().error("提交异常 {} , {}", e.getMessage(),e);
			return new ResponseEntity<>(new ResponseBaseModel(29002,e.getMessage()), HttpStatus.OK);
		}
	}
	
	/***
	 * 补推送正确的开奖号码
	 * @param 
	 * @return
	 */
	@RequestMapping(value="/update_push_opencode")
	public @ResponseBody ResponseEntity<?> update_push_opencode(HttpServletRequest req , CaiPiaoOpencode openCode) {
		try {
			if(StringUtils.isBlank(openCode.getCaiId())) {
				return new ResponseEntity<>(new ResponseBaseModel(29002,"参数caiId 不能为空"), HttpStatus.OK);
			}
			if(StringUtils.isBlank(openCode.getIssueno()) || openCode.getIssueno().length() < 8) {
				return new ResponseEntity<>(new ResponseBaseModel(29002,"期号为空，或期号长度错误! "), HttpStatus.OK);
			}
			getLoger().error("提交的数据为: " + JSONObject.toJSONString(openCode));
			return caiPiaoService.update_push_opencode(openCode);
		}catch(Exception e) {
			this.getLoger().error("提交异常 {} , {}", e.getMessage(),e);
			return new ResponseEntity<>(new ResponseBaseModel(29002,e.getMessage()), HttpStatus.OK);
		}
	}
	
		
	
	/***
	 * 获取系统当前时间
	 * @param req
	 * @param info
	 * @return
	 */
	@RequestMapping(value="/getnow",method = RequestMethod.POST)
	public @ResponseBody ResponseEntity<?> getServiceDateTime(HttpServletRequest req) {
		try {
			Map<String,Object> _map = new HashMap<String,Object>();
			_map.put("time", new Date().getTime());
			return new ResponseEntity<>(new ResponseResultModel<Map<String,Object>>(_map),HttpStatus.OK);
		}catch(Exception e) {
			this.getLoger().error("登录异常 {} , {}", e.getMessage(),e);
			return new ResponseEntity<>(new ResponseBaseModel(29002,e.getMessage()), HttpStatus.OK);
		}
	}
	
	
	@RequestMapping(value="/pullcodelist",method = RequestMethod.POST)
	public @ResponseBody ResponseEntity<?> pullcodelist(HttpServletRequest req ,@RequestBody CustomCaiPiaoOpencode openCode) {
		try {
		    if(getRequestHeader(req) == null || StringUtils.isBlank(getRequestHeader(req).getCaiId())) {
		    	return new ResponseEntity<>(new ResponseBaseModel(29002,"缺少请求头参数"), HttpStatus.OK);
		    }
			int _dataCount = 0;
		    if(StringUtil.isNotBlank(openCode.getDataCount())) {
		    	_dataCount = Integer.parseInt(openCode.getDataCount());
		    }
		    CustomCaiPiaoOpencode _cCaiPiaoOpencode = new CustomCaiPiaoOpencode();
		    _cCaiPiaoOpencode.setCaiId(getRequestHeader(req).getCaiId());
		    
		    List<CaiPiaoOpencode> _list = null;
		    if(_dataCount != 0) {
		    	_cCaiPiaoOpencode.orderById(false);
		    	PageHelper.startPage(1, _dataCount);
		    	_list =  caiPiaoOpencodeService.queryAll(_cCaiPiaoOpencode);
		    }else {
		    	if(StringUtil.isBlank(openCode.getDateStr())) {
		    		_cCaiPiaoOpencode.orderById(false);
		    		PageHelper.startPage(1, 3000);
			    	_list =  caiPiaoOpencodeService.queryAll(_cCaiPiaoOpencode);
		    	}else {
		    		_cCaiPiaoOpencode.setIssueno(openCode.getDateStr());
		    		_list = caiPiaoOpencodeService.getCustomMapper().selectAllLikeDate(_cCaiPiaoOpencode);
		    	}
		    }
		    
		    if(CollectionUtils.isNotEmpty(_list)) {
				Collections.reverse(_list);
			}
		    
		    for(CaiPiaoOpencode cai : _list) {
				cai.setExtend1(String.valueOf(cai.getOpendate().getTime()));
			}
			
			@SuppressWarnings("unused")
			String issno = null;
			if(CollectionUtils.isNotEmpty(_list)) {
				CaiPiaoOpencode _c = _list.get(_list.size() - 1);
				issno = _c.getIssueno();
			}
			CaiPiaoOpenTime openTime = caiPiaoOpencodeService.getNextOpenCodeTime(Long.valueOf(getRequestHeader(req).getCaiId()));
			Map<String,Object> ret = new HashMap<String,Object>();
			ret.put("list", _list);
			ret.put("nextOpenTime", openTime);
			return new ResponseEntity<>(new ResponseResultModel<Map<String,Object>>(ret),HttpStatus.OK);
			
			
		}catch(Exception e) {
			this.getLoger().error("获取彩票开奖号码异常 {} , {}", e.getMessage(),e);
			return new ResponseEntity<>(new ResponseBaseModel(29002,e.getMessage()), HttpStatus.OK);
		}
	}
	
	
	@RequestMapping(value="/pullcodelist3",method = RequestMethod.POST)
	public @ResponseBody ResponseEntity<?> pullcodelist3(HttpServletRequest req ,@RequestBody CustomCaiPiaoOpencode openCode) {
		try {
		    if(getRequestHeader(req) == null || StringUtils.isBlank(getRequestHeader(req).getCaiId())) {
		    	return new ResponseEntity<>(new ResponseBaseModel(29002,"缺少请求头参数"), HttpStatus.OK);
		    }
			CustomCaiPiaoOpencode _cCaiPiaoOpencode = new CustomCaiPiaoOpencode();
			_cCaiPiaoOpencode.setCaiId(getRequestHeader(req).getCaiId());
			_cCaiPiaoOpencode.orderByIssueno(false);
			if(StringUtils.isNotBlank(openCode.getStartIssueno())) {
				_cCaiPiaoOpencode.setStartIssueno(openCode.getStartIssueno());
			}
			if(StringUtils.isNotBlank(openCode.getEndIssueno())){
				_cCaiPiaoOpencode.setEndIssueno(openCode.getEndIssueno());
			}
			PageHelper.startPage(1, 3000);
			List<CaiPiaoOpencode> _list = caiPiaoOpencodeService.getCustomMapper().selectAllByCaiId(_cCaiPiaoOpencode);
			if(CollectionUtils.isNotEmpty(_list)) {
				Collections.reverse(_list);
			}
			for(CaiPiaoOpencode cai : _list) {
				cai.setExtend1(String.valueOf(cai.getOpendate().getTime()));
			}
			
			@SuppressWarnings("unused")
			String issno = null;
			if(CollectionUtils.isNotEmpty(_list)) {
				CaiPiaoOpencode _c = _list.get(_list.size() - 1);
				issno = _c.getIssueno();
			}
			CaiPiaoOpenTime openTime = caiPiaoOpencodeService.getNextOpenCodeTime(Long.valueOf(getRequestHeader(req).getCaiId()));
			Map<String,Object> ret = new HashMap<String,Object>();
			ret.put("list", _list);
			ret.put("nextOpenTime", openTime);
			return new ResponseEntity<>(new ResponseResultModel<Map<String,Object>>(ret),HttpStatus.OK);
		}catch(Exception e) {
			this.getLoger().error("获取彩票开奖号码异常 {} , {}", e.getMessage(),e);
			return new ResponseEntity<>(new ResponseBaseModel(29002,e.getMessage()), HttpStatus.OK);
		}
	}
	
	
	
	@RequestMapping(value="/getcaiidlist",method = RequestMethod.POST)
	public @ResponseBody ResponseEntity<?> getcaiidlist(HttpServletRequest req ) {
		try {
			
			Map<String,Object> retMap = null;
			List<Map<String,Object>> retList = new ArrayList<Map<String,Object>>();
			List<CaiType> list = caiTypeService.queryAll(new CaiType());
			for(CaiType ct : list) {
				retMap = new HashMap<String,Object>();
				 Long ctypeid = ct.getId();
				 CaiPiao vo = new CaiPiao();
				 vo.setCaiTypeId(String.valueOf(ctypeid));
				 List<CaiPiao> list2 = caiPiaoService.queryAll(vo);
				 retMap.put("id", ct.getId());
				 retMap.put("caiTypeName", ct.getCaiTypeName());
				 retMap.put("list", list2);
				 retList.add(retMap);
			}
			return new ResponseEntity<>(new ResponseResultModel<List<Map<String,Object>>>(retList),HttpStatus.OK);
		}catch(Exception e) {
			this.getLoger().error("登录异常 {} , {}", e.getMessage(),e);
			return new ResponseEntity<>(new ResponseBaseModel(29002,e.getMessage()), HttpStatus.OK);
		}
	}
	
	
	
	@RequestMapping(value="/update",method = RequestMethod.GET)
	public @ResponseBody ResponseEntity<?> update(HttpServletRequest req ) {
		int pageSize = 1000;
		try {
			CaiPiaoOpencodeBackup backup = new CaiPiaoOpencodeBackup();
			backup.orderById(false);
			backup.setNumber9("1");
			PageHelper.startPage(1,pageSize);
			List<CaiPiaoOpencodeBackup> plist = caiPiaoOpencodeBackupService.queryAll(backup);
			while(CollectionUtils.isNotEmpty(plist)) {
				Long begin = new Date().getTime();
				caiPiaoOpencodeBackupService.updateOpen(plist);
				PageHelper.startPage(1, pageSize);
				plist = caiPiaoOpencodeBackupService.queryAll(backup);
			}
			return new ResponseEntity<>(new ResponseResultModel<String>("ok"),HttpStatus.OK);
		}catch(Exception e) {
			this.getLoger().error("登录异常 {} , {}", e.getMessage(),e);
			return new ResponseEntity<>(new ResponseBaseModel(29002,e.getMessage()), HttpStatus.OK);
		}
	} 
	
	@RequestMapping(value="/testredis",method = RequestMethod.POST)
	public @ResponseBody ResponseEntity<?> testredis(HttpServletRequest req) {
		try {
			
			//return caiPiaoMissCodeListService.testRedis();
			//caiPiaoMissCodeListService.writeRedis(101L);
			//caiPiaoMissCodeListService.readRedis(101L);
			//caiPiaoMissCodeListService.initMissCodeToSystemRam();
			return new ResponseEntity<>(new ResponseResultModel<String>("ok"),HttpStatus.OK); 
		}catch(Exception e) {	
			this.getLoger().error("REDIS op 异常 {} , {}", e.getMessage(),e);
			return new ResponseEntity<>(new ResponseBaseModel(29002,e.getMessage()), HttpStatus.OK);
		}
	}
	
	@RequestMapping(value="/initmap",method = RequestMethod.GET)
	public @ResponseBody ResponseEntity<?> initSystemMap(HttpServletRequest req) {
		try {			
			caiPiaoMissCodeListService.initMissCodeToSystemRam();
			//caiPiaoMissCodeListService.readRedis(101L);
			//caiPiaoMissCodeListService.computeOpenCodeMissValue();
			return new ResponseEntity<>(new ResponseResultModel<String>("ok"),HttpStatus.OK);
		}catch(Exception e) {
			this.getLoger().error("REDIS op 异常 {} , {}", e.getMessage(),e);
			return new ResponseEntity<>(new ResponseBaseModel(29002,e.getMessage()), HttpStatus.OK);
		}
	}
	
	@RequestMapping(value="/missCodeCommit",method = RequestMethod.GET)
	public @ResponseBody ResponseEntity<?> missCodeCommit(HttpServletRequest req , CaiOpenInfoV2 info) {
		try {
			if(StringUtils.isBlank(info.getCaiId())) {
				return new ResponseEntity<>(new ResponseBaseModel(29002,"参数cai_id 不能为空"), HttpStatus.OK);
			}
			if(info.getIssueNo() == null && info.getIssueNo().length() < 8) {
				return new ResponseEntity<>(new ResponseBaseModel(29002,"期号为空，或期号长度错误! "), HttpStatus.OK);
			}
			return caiPiaoOpencodeService.missCodeCommit(info.getOpenCode(), info.getIssueNo(), info.getCaiId(), info.getOpenTime());
		}catch(Exception e) {
			this.getLoger().error("漏号提交异常 {} , {}", e.getMessage(),e);
			return new ResponseEntity<>(new ResponseBaseModel(29002,e.getMessage()), HttpStatus.OK);
		}
	}
	
	
	@RequestMapping(value="/misscodenotice",method = RequestMethod.GET)
	public @ResponseBody ResponseEntity<?> misscodenotice(HttpServletRequest req , CaiOpenInfoV2 info) {
		try {
			if(StringUtils.isBlank(info.getCaiId())) {
				return new ResponseEntity<>(new ResponseBaseModel(29002,"参数cai_id 不能为空"), HttpStatus.OK);
			}
			
			CaiPiao _queryCaiPiao = new CaiPiao();
			_queryCaiPiao.setCaiId(Integer.parseInt(info.getCaiId()));
			
			List<CaiPiao> caiPiaoList = caiPiaoService.queryAll(_queryCaiPiao);
			String cName = "";
			if(CollectionUtils.isNotEmpty(caiPiaoList)) {
				cName = caiPiaoList.get(0).getCaiName();
			}
			
			
			CEvenyDayOpenTime cEvenyDayOpenTime = new CEvenyDayOpenTime();
			cEvenyDayOpenTime.setCaiId(Long.valueOf(info.getCaiId()));
			CEvenyDayOpenTime prvoOpenCodeInfo = evenyDayOpenTimeService.selectPrevOpenTime(cEvenyDayOpenTime);
			String msg = "";
			if(prvoOpenCodeInfo == null) {
				msg = cName + ":" + info.getCaiId() + "当前出现了漏号, 但是在eveny_day_open_time表中未查到期数据";
			}else {
				CaiPiaoOpencode queryCaiPiaoOpencode = new CaiPiaoOpencode();
				queryCaiPiaoOpencode.setCaiId(info.getCaiId());
				queryCaiPiaoOpencode.setIssueno(prvoOpenCodeInfo.getIssueno());
				int count = caiPiaoOpencodeService.queryAllCount(queryCaiPiaoOpencode);
				if(count < 1) {
					msg = cName + ":" + info.getCaiId() + "当前出现了漏号, 期号 : " + prvoOpenCodeInfo.getIssueno();
				}else {
					return null;
				}
			}
			SysRestrictionsConfig config = sysRestrictionsConfigService.getSysRestrictionsConfig("sysnoticemail");
			if(config == null) {
				throw new Exception("未配置socket服务器相关信息,请从数据进行配置!");
			}
			
			Mail mail = new Mail();
			mail.setReceive(config.getName());
			mail.setSubject("开奖号码漏号提醒邮件");
			mail.setMsg(msg);
			mailService.asynchronousSendMail(mail);
			return new ResponseEntity<>(new ResponseResultModel<String>("漏号提醒成功"),HttpStatus.OK);
			//return caiPiaoOpencodeService.missCodeCommit(info.getOpenCode(), info.getIssueNo(), info.getCaiId(), info.getOpenTime());
		}catch(Exception e) {
			this.getLoger().error("漏号提交异常 {} , {}", e.getMessage(),e);
			return new ResponseEntity<>(new ResponseBaseModel(29002,e.getMessage()), HttpStatus.OK);
		}
	}
	
}

